/**
 * Project Name:vip-concurrent
 * File Name:ForkJoinTest.java
 * Package Name:com.libra.cn
 * Date:2018年8月27日上午11:00:05
 * Copyright (c) 2018, wangzhch All Rights Reserved.
 *
*/

package com.libra.config;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.RecursiveTask;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ClassName:ForkJoinTest <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason:	 TODO ADD REASON. <br/>
 * Date:     2018年8月27日 上午11:00:05 <br/>
 * @author   wangzhch
 * @version  
 * @since    JDK 1.8
 * @see 	 
 */
public class ForkJoinTest  extends RecursiveTask<Integer>{
	Logger log = LoggerFactory.getLogger(ForkJoinTest.class);
		
		/**
		 * serialVersionUID:TODO(用一句话描述这个变量表示什么).
		 * @since JDK 1.8
		 */
		private static final long serialVersionUID = 122981129288088436L;
		
		private OutputStream os;
		private int beginIndex; //开始下标
		private int endIndex; //结束下标
		private File file;
		private static int CUT_SIZE = 1000000;

		public ForkJoinTest(OutputStream os, int beginIndex, int l, File file) {
			super();
			this.os = os;
			this.beginIndex = beginIndex;
			this.endIndex = l;
			this.file = file;
		}


		@Override
		protected Integer compute() {
			BufferedInputStream bis = null;
			try {
				bis = new BufferedInputStream(new FileInputStream(file));
				
				if(endIndex - beginIndex < CUT_SIZE) {
					byte[] buff = new byte[endIndex];
					int i = bis.read(buff);
					while (i != -1) {
						os.write(buff, 0, endIndex);
//						os.write(buff, beginIndex, endIndex);
//						os.close();
						i = bis.read(buff);
					}
				}
				int mid = (beginIndex+endIndex)/2;
				ForkJoinTest left = new ForkJoinTest(os,beginIndex,mid,file); 
				ForkJoinTest right = new ForkJoinTest(os,mid+1, endIndex,file);
				//invokeAll等线程任务执行完毕后,取得全部任务的结果值
				invokeAll(left, right);
				return left.join()+right.join();
			} catch (FileNotFoundException e1) {
				log.info("FileNotFoundException:{}",e1.getMessage());
			}catch (IOException e) {
				log.info("异常:{}",e.getMessage());
			} finally {
				try {
					if (bis != null) {
						bis.close();
					}
					if(os != null) {
						
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return 0;
		}
//		public static void main(String[] args) {
//			int[] ints = createArray();
//			System.out.println(ints.length);
//			MyTask myTask = new MyTask(ints, 0, ints.length-1);
//			
//			ForkJoinPool forkJoinPool = new ForkJoinPool();
//			forkJoinPool.invoke(myTask);
//			Integer num = myTask.join();
//			System.out.println("num:"+num);
//		}
	}
	

